<template>
  <el-dialog v-model="dialogVisible" title="Tips" width="30%">
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">Check
      all</el-checkbox>
    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
      <el-checkbox v-for="col in columns" :key="col.key" :label="col.title">{{ col.title }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="confirm">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

const emit = defineEmits(['update:columns'])
const props = defineProps(['columns'])
const dialogVisible = ref(false)
const checkAll = ref(true)
const isIndeterminate = ref(false)
const checkedCities = ref(<any>[])
const generateColumns = (length = 10, prefix = 'column-', props?: any) =>
  Array.from({ length }).map((_, columnIndex) => ({
    ...props,
    key: `${prefix}${columnIndex}`,
    dataKey: `${prefix}${columnIndex}`,
    title: `Column ${columnIndex}`,
    width: 150,
    checked: false
  }))
let columns = generateColumns(10)
const show = () => {
  props.columns.forEach((item: any, index: number) => {
    if (item.key === columns[index].key) {
      columns[index].checked = true
    }
  })
  checkedCities.value = props.columns.map((item: any) => item.title)
  console.log(checkedCities.value);
  dialogVisible.value = true
}

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? columns.map(item => item.title) : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === columns.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < columns.length
}
const confirm = () => {
  dialogVisible.value = false
  let list: any[] = []
  columns.forEach(item => {
    checkedCities.value.forEach((k: any) => {
      if (item.title === k) {
        list.push({
          ...item
        })
      }
    })
  })
  emit('update:columns', list)
}
defineExpose({
  show
})
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
